package scala.cookbook.akka

import akka.actor.Actor.Receive
import akka.actor._

/**
  * Created by shichen on 2017/5/9.
  *
  * 一部分文件代码来自 scala cookbook
  */
case object PingMessage
case object PongMessage
case object StartMessage
case object StopMessage

class Ping(pong: ActorRef) extends Actor {
  var count = 0

  def increAndPrint {
    count += 1; println("ping")
  }

  override def receive: Receive = {
    case StartMessage =>
      increAndPrint
      pong ! PingMessage
    case PongMessage =>
      increAndPrint
      if (count > 10) {
        sender() ! StopMessage
        println("ping stopped")
        context.stop(self)
      } else {
        sender() ! PingMessage
      }
    case _ => println("upexpected")
  }
}

class Pong extends Actor {
  override def receive: Receive = {
    case PingMessage =>
      println(" pong")
      sender ! PongMessage
    case StopMessage =>
      println("pong stopped")
      context.stop(self)
    case _ => println("pong got unexpected")
  }
}

class ScalaPongActor extends Actor {
  override def receive: Receive = {
    case "Ping" => sender() ! "Pong"
    case _ => sender() ! Status.Failure(new Exception("unknown message"))
  }

}

object PingPongTest extends App {
  val system = ActorSystem("PingPongSystem")
  val pong = system.actorOf(Props[Pong], name = "pong")
  val ping = system.actorOf(Props(new Ping(pong)), name = "ping")

  ping ! StartMessage
}
